package com.liuqi.knet.rpc.cluster;

import com.liuqi.knet.remoting.RemotingException;
import java.util.List;

/**
 * @author liuqi
 * @date 2025/3/6 15:26
 **/
public abstract class AbstractLoadBalance implements LoadBalance {

    private final LoadBalanceNode loadBalanceNode;

    public AbstractLoadBalance(ClusterConfig clusterConfig) {
        this.loadBalanceNode = clusterConfig.getBalanceNode();
        if (this.loadBalanceNode == null || this.loadBalanceNode.getNodes().isEmpty()) {
            throw new NullPointerException("集群节点配置为空, node: " + this.loadBalanceNode);
        }
    }

    @Override
    public LoadBalanceNode.Node select() throws RemotingException {
        List<LoadBalanceNode.Node> nodes = this.loadBalanceNode.getNodes();
        if (nodes.size() == 1) {
            return nodes.get(0);
        }
        return doSelect();
    }

    @Override
    public int nodes() {
        return loadBalanceNode.getNodes().size();
    }

    public LoadBalanceNode getLoadBalanceNode() {
        return this.loadBalanceNode;
    }

    protected abstract LoadBalanceNode.Node doSelect() throws RemotingException;

}
